package de.tum.in.eist.poll.client;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.HeadingElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.shared.User;

/**
 * Startpage of the program
 * 
 * @author florian
 * 
 */
public class Startpage extends Webpage {

	/**
	 * Username of the lecturer or student.
	 */
	private TextBox user;

	/**
	 * Password
	 */
	private TextBox password;

	private OnSuccessfulLoginHandler onSuccessfulLoginHandler;

	@Override
	public final void loadWebsite() {
		// Create webpage elements
		user = new TextBox();
		DOM.setElementAttribute(user.getElement(), "id", "user");
		password = new PasswordTextBox();
		DOM.setElementAttribute(password.getElement(), "id", "password");
		Button submit = new Button("Submit");
		DOM.setElementAttribute(submit.getElement(), "id", "login");
		submit.addClickHandler(submitLogin);
		Label userL = new Label("User:");
		Label passwordL = new Label("Password:");

		HTMLPanel panel = new HTMLPanel("");

		VerticalPanel p = new VerticalPanel();
		// Create title
		HeadingElement e = Document.get().createHElement(1);
		e.setId("Login");
		e.setInnerText("Login");
		panel.getElement().appendChild(e);
		panel.add(p);

		// add form to the panel
		p.add(userL);
		p.add(user);
		p.add(passwordL);
		p.add(password);
		p.add(submit);

		setContent(panel);
	}

	/**
	 * Handler for the submitting of the Login Data.
	 */
	private ClickHandler submitLogin = new ClickHandler() {

		@Override
		public void onClick(final ClickEvent event) {
			// Set up the callback object.
			AsyncCallback<User> callback = new AsyncCallback<User>() {
				public void onFailure(final Throwable caught) {
					// TODO: Do something with errors.
					assert(true);
				}

				public void onSuccess(final User result) {
					if (result != null) {
						if (onSuccessfulLoginHandler != null) {
							onSuccessfulLoginHandler.successfulLogin(result);
						}
					} else {
						com.google.gwt.user.client.Window
								.alert("Not logged in");
					}
				}
			};

			getService().login(user.getText(), password.getText(), callback);
		}
	};

	/**
	 * Sets the Handler for a successful login.
	 * 
	 * @param handler
	 *            Handler to call
	 */
	public final void setOnSuccessfulLoginHandler(
			final OnSuccessfulLoginHandler handler) {
		onSuccessfulLoginHandler = handler;
	}
}
